package com.example.zjx8969.myapplication.jobscheduler;

import android.annotation.TargetApi;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Build;
import android.util.Log;

import java.util.concurrent.Executors;

import threads.PriorityThreadPool;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobSchedulerService extends JobService {
    JobParameters jobParameters;

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.e("tag", "onStartJob ^");
        this.jobParameters = params;
        PriorityThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 100; i >= 0; i--) {
                    long v = (long) (Math.random() * 100);
                    try {
                        Thread.sleep(v);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e("tag", jobParameters.getJobId() + " sleep " + v);
                }
                jobFinished(jobParameters, false);
            }
        });
        // 返回true，表示该工作耗时，同时工作处理完成后需要调用onStopJob销毁（#jobFinished）
        // 返回false，任务运行不需要很长时间，到return时已完成任务处理
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.e("tag", "onStopJob ^");
        // 有且仅有onStartJob返回值为true时，才会调用onStopJob来销毁job
        // 返回false来销毁这个工作
        return false;
    }
}
